package com.smartcruise.util.network;

import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.google.gson.Gson;
import com.smartcruise.base.BaseNormalView;
import com.smartcruise.data.ReportData;
import com.smartcruise.util.FileUtils;
import com.smartcruise.util.ListUtils;
import com.smartcruise.util.image.ImageUtils;
import com.smartcruise.util.network.callBack.BaseCallBack;
import com.smartcruise.util.network.callBack.SimpleCallBack;
import com.smartcruise.util.network.callBack.UploadFileCallBack;
import com.smartcruise.util.network.customerObserver.SimpleProgressObserverImp;
import com.smartcruise.util.network.netUtils.NetCollection;
import com.smartcruise.util.network.netUtils.Result;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.realm.Realm;

/**
 * Created by FengChaoQun
 * on 2018/3/5 0005
 * 通报数据上传
 */

public class ReportUpload {

    private boolean allUpload;//是否全部上传
    private BaseNormalView mView;
    private ReportData reportData;//要上传的数据
    private BaseCallBack baseCallBack;//回调
    private boolean needCloseDialog = true;

    public ReportUpload(BaseNormalView mView, ReportData reportData) {
        this.mView = mView;
        this.reportData = reportData;
    }

    /**
     * description:上传一个通报的简略信息
     */

    public void uploadOneNodeSimpleData(BaseCallBack baseCallBack) {

        this.baseCallBack = baseCallBack;
        allUpload = false;

        //先上传节点任务图片和视频
        List<String> imageList = reportData.getOriginalImage();
        List<String> videoList = reportData.getOriginalVideos();
        List<String> audioList = reportData.getOriginalAudios();

        //先压缩文件 再上传文件 最后上传到服务器
        uploadFile(imageList, videoList, audioList, new SimpleCallBack(mView) {
            @Override
            public void onSuccess(Result result) {
                mView.getRealm().executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {//整理数据
                        reportData.buildTaskSimpleData();
                        Log.d("NodeTaskDataEditPresent", "" + reportData.getContentMap());
                    }
                });
                uploadTaskData();
            }
        });

    }

    /**
     * description:上传一个通报的全部信息
     * 1.先上传缩略图信息
     * 2.再上传原图信息
     * 3.整体数据上传
     */

    public void uploadOneNodeAllData(BaseCallBack baseCallBack) {

        this.baseCallBack = baseCallBack;
        allUpload = true;

        //先上传节点任务图片和视频
        final List<String> imageList = reportData.getOriginalImage();
        final List<String> videoList = reportData.getOriginalVideos();
        final List<String> audioList = reportData.getOriginalAudios();


        //1.上传缩略图
        uploadFile(imageList, videoList, audioList, new SimpleCallBack(mView) {
            @Override
            public void onSuccess(Result result) {
                mView.getRealm().executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {//整理数据
                        reportData.buildTaskSimpleData();
                        Log.d("NodeTaskDataEditPresent", "" + reportData.getContentMap());
                    }
                });

                Map<String, String> map = new HashMap<>();
                if (ListUtils.isHaveContent(imageList)) {
                    for (String s : imageList) {
                        map.put(FileUtils.getFileSimpleName(s), s);
                    }
                }
                if (ListUtils.isHaveContent(videoList)) {
                    for (String s : videoList) {
                        map.put(FileUtils.getFileSimpleName(s), s);
                    }
                }
                if (ListUtils.isHaveContent(audioList)) {
                    for (String s : audioList) {
                        map.put(FileUtils.getFileSimpleName(s), s);
                    }
                }

                //2.然后上传原图
                uploadFile(map, new SimpleCallBack(mView) {
                    @Override
                    public void onSuccess(Result result) {
                        mView.getRealm().executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {//整理数据
                                reportData.buildTaskAllData();
                                Log.d("NodeTaskDataEditPresent", "" + reportData.getContentMap());
                            }
                        });
                        //3.最后上传整体数据
                        uploadTaskData();
                    }
                });
            }
        });

    }

    /**
     * description:先压缩 再上传文件
     */

    private void uploadFile(List<String> imageList, List<String> videoList, final List<String> audioList, final BaseCallBack baseCallBack) {
        ImageUtils.getCompressedData(imageList, videoList, new Observer<Map<String, String>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                mView.showLoadingDialog("正在压缩文件");
            }

            @Override
            public void onNext(Map<String, String> stringStringMap) {
                Log.d("ReportDataPresenterImp", "stringStringMap:" + stringStringMap);
                if (stringStringMap == null || stringStringMap.isEmpty()) {//没有图片和视频数据
                    stringStringMap = new HashMap<>();
                }
                if (audioList != null && !audioList.isEmpty()) {//添加语音数据
                    for (String s : audioList) {
                        stringStringMap.put(FileUtils.getFileSimpleName(s), s);
                    }
                }
                uploadFile(stringStringMap, baseCallBack);
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
                mView.showToast(throwable.getMessage());
                mView.hideLoadingDialog();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * description:上传文件
     */

    private void uploadFile(Map<String, String> data, final BaseCallBack baseCallBack) {

        if (data == null || data.isEmpty()) {//没有需要上传的数据
            baseCallBack.onSuccess(null);
            return;
        }

        FileUpload fileUpload = new FileUpload(data, new UploadFileCallBack() {
            @Override
            public void onStart() {
                mView.showLoadingDialog("开始上传");
            }

            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                final String showText = (int) ((currentSize * 1f / totalSize) * 100) + "%";
                mView.setLoadingDialogText(showText);
            }

            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                baseCallBack.onSuccess(null);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                if (clientExcepion != null) {
                    clientExcepion.printStackTrace();
                    mView.showToast(clientExcepion.getMessage());
                }
                if (serviceException != null) {
                    serviceException.printStackTrace();
                    mView.showToast(serviceException.getRawMessage());
                }
                mView.hideLoadingDialog();
            }
        });
        fileUpload.start();
    }

    /**
     * description:上传数据包
     */

    private void uploadTaskData() {
        final ReportData copyDate = mView.getRealm().copyFromRealm(reportData);
        copyDate.backUpId();
        Gson gson = new Gson();
        Log.d("ReportUpload", "reportDataId:--" + copyDate.getId());

        NetCollection.pushReport(gson.toJson(copyDate), new SimpleProgressObserverImp(mView, new SimpleCallBack(mView) {
            @Override
            public void onSuccess(final Result result) {
                mView.getRealm().executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {

                        //上传成功后 更新服务器id
                        String serverId = result.getData();
                        reportData.setServerId(serverId);

                        //更新数据上传状态
                        if (allUpload) {
                            reportData.setUploadStatus(2);
                        } else {
                            reportData.setUploadStatus(1);
                        }

                        //如果数据是从服务器获取的 则在上传之后要清空本地原数据
                        //因为在展示数据的时候 从服务器获取的数据需要展示本地和服务器的所有数据
                        //如果不清空 则导致数据重复
                        if (reportData.isFromNet()) {
                            reportData.clearOriginalFiles();
                        }
                    }
                });
                baseCallBack.onSuccess(result);
            }
        }) {
            @Override
            public void onComplete() {
                if (needCloseDialog) {
                    super.onComplete();
                }
            }
        });
    }

    public void setNeedCloseDialog(boolean needCloseDialog) {
        this.needCloseDialog = needCloseDialog;
    }

}
